<?php
defined("_VALID_ACCESS") || die('Direct access forbidden');
class SCTV_Warehouse extends Module { 
	private $values;
	private $manager_id;
	public function body()
	{
        // chi cho phep quan ly khu vuc, super admin quan ly kho hang khu vuc
        $current_user = CRM_Contactscommon::get_my_record();
        if (!isset($current_user['access']['area manager']) && !Base_AclCommon::i_am_sa()) {
            return;
        }

		$theme = $this->pack_module('Base/Theme');
		
		ob_start();
        $this->display_employees();
		$table = ob_get_contents();
        ob_end_clean();
				
		$theme->assign('employees', $table);

		$employee = null;
		if(isset($_REQUEST['employee']))
		{
			$employee = $_REQUEST['employee'];
            $this->set_module_variable('employee', $employee);
		}

            ob_start();
        $this->manage();
		$table = ob_get_contents();
        ob_end_clean();
				
		$theme->assign('rb', $table);
			
		$theme->display('area_manager');
	}
	public function display_employees()
	{
		$gb = $this->init_module('Utils/GenericBrowser',null,'employees');
		
		$columns = array(
				array('name'=>__('Name'))
		);
		
		$gb->set_table_columns($columns);
		
		$manager =  CRM_ContactsCommon::get_my_record();
		$this->manager_id = $manager['id'];
        $crists = array('|manager'=>$this->manager_id);
        if(Base_AclCommon::i_am_admin() || Base_AclCommon::i_am_sa())
            $crists['|group']='Technical';

        $order = array(
            'first_name' => 'ASC',
            'last_name' => 'ASC'
        );
        $employees = Utils_RecordBrowserCommon::get_records('contact', $crists, array(), $order);

        $gb_row = $gb->get_new_row();
        $gb_row->add_data(
            '<a' . $this->create_href(array('employee'=>''))  . '>Tất cả</a>'
        );
		
		foreach ($employees as $key => $employee){
			$gb_row = $gb->get_new_row();
			$gb_row->add_data(
			 '<a' . $this->create_href(array('employee'=>$employee['id']))  . '>' . $employee['last_name'] . ' ' . $employee['first_name'] . '</a>'	
			); 
		}	
		
		$this->display_module($gb, array(false),'automatic_display');
	}
	public function display_stock($month, $year, $employee = nul)
	{
		$gb = $this->init_module('Utils/GenericBrowser',null,'stock');		
		$columns = array(
				array('name'=>__('Material'), 'width'=>'70px'),
				array('name'=>__('Beginning Inventory'), 'width'=>'50px'),
				array('name'=>__('Increased Amount'), 'width'=>'50px'),				
				array('name'=>__('Acceptance Amount'), 'width'=>'50px'),
				array('name'=>__('Decreased Amount'), 'width'=>'50px'),
				array('name'=>__('Ending Inventory'), 'width'=>'50px')
			);
		
		$gb->set_table_columns($columns);

        if($employee == null){
            $manager =  CRM_ContactsCommon::get_my_record();
            $is_area_manager = array_key_exists('area manager', $manager['access']);
            if($is_area_manager){
                $records = DB::GetAll('select * from sctv_inventory_area(%d, %d, %d)', array($year, $month, $manager['id']));
            }
            else{
                $records = DB::GetAll('select * from sctv_inventory(%d, %d)', array($year, $month));
            }
        }
        else
		    $records = DB::GetAll('select * from sctv_inventory_employee(%d, %d, %d)', array($year, $month, $employee));
		
		foreach ($records as $key=>$record)
		{
			$gb_row = $gb->get_new_row();
			$gb_row->add_data(SCTV_MaterialCommon::material_format($record['material']), $record['beginning'], $record['increase'], $record['acceptance'], $record['other'], $record['ending']);						
		}

        $this->display_module($gb, array(false),'automatic_display');

        if($employee == null){
            $gb = $this->init_module('Utils/GenericBrowser',null,'nhanvien');
            $columns = array(
                array('name'=>__('Material'), 'width'=>'70px'),
                array('name'=>__('Beginning Inventory'), 'width'=>'50px'),
                array('name'=>__('Increased Amount'), 'width'=>'50px'),
                array('name'=>__('Acceptance Amount'), 'width'=>'50px'),
                array('name'=>__('Decreased Amount'), 'width'=>'50px'),
                array('name'=>__('Ending Inventory'), 'width'=>'50px')
            );

            $gb->set_table_columns($columns);

            if($is_area_manager){
                $records = DB::GetAll('select * from sctv_inventory_all_employee_area(%d, %d, %d)', array($year, $month, $manager['id']));
            }
            else
                $records = DB::GetAll('select * from sctv_inventory_all_employee(%d, %d)', array($year, $month));

            $prev_employee = null;
            foreach ($records as $key=>$record)
            {
                $any_employee = $record['employee'];
                if($prev_employee == null || $prev_employee != $any_employee){
                    $prev_employee = $any_employee;
                    $gb_row = $gb->get_new_row();
                    $gb_row->add_data('<strong>'.CRM_ContactsCommon::contact_format_no_company($any_employee).'</strong>', '', '', '', '', '');
                }
                $gb_row = $gb->get_new_row();
                $gb_row->add_data(SCTV_MaterialCommon::material_format($record['material']), $record['beginning'], $record['increase'], $record['acceptance'], $record['other'], $record['ending']);
            }

            $this->display_module($gb, array(false),'automatic_display');
        }
	}
	public function manage()
	{
        $manager =  CRM_ContactsCommon::get_my_record();

		$form = $this->init_module('Libs/QuickForm');
		
		$prompt_delivery_to_employee_id = "new_delivery_to_employee";			
        $content_delivery = $this->leightbox_new_delivery($prompt_delivery_to_employee_id);
		
		if($this->values['submited'] == 1)
		{
			$id = $this->save_delivery_to_employee();
			
			$rb = $this->init_module('Utils_RecordBrowser', 'SCTV_DeliveryToEmployee');
			$this->display_module($rb, array('view', $id, array(), array()), 'view_entry');
			
			$this->values = array();
			return;
		}
		
		$prompt_receive_from_employee_id = "new_receive_from_employee";			
        $content_receive = $this->leightbox_new_receive($prompt_receive_from_employee_id);
		
		if($this->values['submited'] == 1)
		{
			$id = $this->save_receive_from_employee();
			
			$rb = $this->init_module('Utils_RecordBrowser', 'SCTV_ReceiveFromEmployee');
			$this->display_module($rb, array('view', $id, array(), array()), 'view_entry');
			
			$this->values = array();
			return;
		}
				
		Libs_LeightboxCommon::display($prompt_delivery_to_employee_id, $content_delivery, __('Delivery to employee'), 1);                       
		Libs_LeightboxCommon::display($prompt_receive_from_employee_id, $content_receive, __('Receive from employee'), 1);

        $employee = $this->get_module_variable('employee', null);

        if(isset($_REQUEST['month']))
            $this->set_module_variable('month', $_REQUEST['month']);

        if(isset($_REQUEST['year']))
            $this->set_module_variable('year', $_REQUEST['year']);

        $month = intval($this->get_module_variable('month', date('m')));
        $year = $this->get_module_variable('year', date('Y'));

        $form->addElement('select', 'month', 'Tháng', array(1=>1, 2=>2, 3=>3, 4=>4, 5=>5, 6=>6, 7=>7, 8=>8, 9=>9, 10=>10, 11=>11, 12=>12), array('onchange'=>$form->get_submit_form_js(false)));
        $form->addElement('select', 'year', 'Năm', array(2014=>2014, 2015=>2015, 2016=>2016, 2017=>2017, 2018=>2018), array('onchange'=>$form->get_submit_form_js(false)));

		$form->addElement('header', null, $employee==null?'Tất cả':CRM_ContactsCommon::contact_format_default($employee, true));
		$form->addElement('button', 'new_delivery_to_employee', __('Add new') . ' ' . __('Delivery to Employee'), Libs_LeightboxCommon::get_open_href($prompt_delivery_to_employee_id));					
		$form->addElement('button', 'new_receive_from_employee', __('Add new') . ' ' . __('Receive from Employee'), Libs_LeightboxCommon::get_open_href($prompt_receive_from_employee_id));

        $form->setDefaults(array('month'=>$month, 'year'=>$year));
				
		$form->display_as_row();
		$this->display_stock($month, $year, $employee);

        $from_date = mktime(0, 0, 0, $month, 1, $year);
        $to_date = date('Y-m-t', $from_date);
        $from_date = date('Y-m-d', $from_date);

        $crits = array('>=delivery_date'=>$from_date, '<=delivery_date'=>$to_date);
        if($employee == null){
            $this->manager_id = $manager['id'];
            $employees = Utils_RecordBrowserCommon::get_records('contact', array('manager'=>$this->manager_id));
            $employees = array_column($employees, 'id');
            $crits['employee'] = $employees;
        }
        else{
            $crits['employee'] = $employee;
        }

        $date = null;

		$deliveries = Utils_RecordBrowserCommon::get_records('SCTV_DeliveryToEmployee', $crits, null, array('delivery_date'=>'desc'));
		foreach ($deliveries as $key => $delivery){
            $delivery_date = $delivery['delivery_date'];
            if($delivery_date != $date){
                if($date != null)
                    $this->display_module($gb, array(false),'automatic_display');
                $date = $delivery_date;
                $date_string = date('d-m-Y', strtotime($date));
                $keymd5 = md5(time());
                $_SESSION[$keymd5] = array(
                    'manager'=>$manager['id']
                );
                $print_href = 'href="modules/SCTV/Warehouse/print_delivery_area.php?'.http_build_query(array('key'=>$keymd5, 'cid'=>CID, 'manager'=>$manager['id'], 'date'=>$date)).'" target="_blank"';

                $gb = $this->init_module('Utils/GenericBrowser',null,$date_string);
                $columns = array(
                    array('name'=>__('Giao/Nhận'), 'width'=>'30px'),
                    array('name'=>'<a ' . $print_href . '>In phiếu đề nghị ' . $date_string . '</a>', 'width'=>'70px'),
                    array('name'=>__('Employee'), 'width'=>'120px'),
                    array('name'=>__('Note'), 'width'=>'150px')
                );

                $gb->set_table_columns($columns);
            }
			$gb_row = $gb->get_new_row();
			$gb_row->add_data('Giao', $date_string, CRM_ContactsCommon::contact_format_default($delivery['employee']), $delivery['note']);
			$gb_row->add_action(Utils_RecordBrowserCommon::create_record_href('SCTV_DeliveryToEmployee', $delivery['id']),__('View')); 
		}

        if($date != null)
            $this->display_module($gb, array(false),'automatic_display');

        $crits = array('>=receive_date'=>$from_date, '<=receive_date'=>$to_date);
        if($employee == null){
            $manager =  CRM_ContactsCommon::get_my_record();
            $this->manager_id = $manager['id'];
            $employees = Utils_RecordBrowserCommon::get_records('contact', array('manager'=>$this->manager_id));
            $employees = array_column($employees, 'id');
            $crits['employee'] = $employees;
        }
        else{
            $crits['employee'] = $employee;
        }

        $date = null;
		$receivers = Utils_RecordBrowserCommon::get_records('SCTV_ReceiveFromEmployee', $crits, null, array('receive_date'=>'desc'));
		foreach ($receivers as $key => $receive){
            $receive_date = $receive['receive_date'];
            if($receive_date != $date){
                if($date != null)
                    $this->display_module($gb, array(false),'automatic_display');
                $date = $receive_date;
                $date_string = date('d-m-Y', strtotime($date));
                $gb = $this->init_module('Utils/GenericBrowser',null,$date_string);
                $columns = array(
                    array('name'=>__('Giao/Nhận'), 'width'=>'30px'),
                    array('name'=>__('Date'), 'width'=>'70px'),
                    array('name'=>__('Employee'), 'width'=>'120px'),
                    array('name'=>__('Note'), 'width'=>'150px')
                );

                $gb->set_table_columns($columns);
            }
			$gb_row = $gb->get_new_row();
			$gb_row->add_data('Nhận', $date_string, CRM_ContactsCommon::contact_format_default($receive['employee']), $receive['note']);
			$gb_row->add_action(Utils_RecordBrowserCommon::create_record_href('SCTV_ReceiveFromEmployee', $receive['id']),__('View')); 
		}

        if($date != null)
            $this->display_module($gb, array(false),'automatic_display');
	}
	public function delivery_material_addon($arg)
	{
        $keymd5 = md5(time());
        $_SESSION[$keymd5] = array(
            'id'=>$arg['id'],
        );
        $print_href = 'href="modules/SCTV/Warehouse/print_delivery.php?'.http_build_query(array('key'=>$keymd5, 'cid'=>CID, 'id'=>$arg['id'])).'" target="_blank"';

        Base_ActionBarCommon::add('print', __('Print'), $print_href);

		$rb = $this->init_module('Utils/RecordBrowser','SCTV_DeliveryMaterial');
		//$rb->disable_actions();
			$rb->disable_pdf();
			$rb->disable_export();
			$rb->disable_filters();
			$rb->disable_search();			
		$rb->set_defaults(array('delivery'=>$arg['id']));
		$rpm = array(array('delivery'=>$arg['id']), array(), array());
		$this->display_module($rb,$rpm,'show_data');
	}
	public function receive_material_addon($arg)
	{
		
		$rb = $this->init_module('Utils/RecordBrowser','SCTV_ReceiveMaterial');
		//$rb->disable_actions();
			$rb->disable_pdf();
			$rb->disable_export();
			$rb->disable_filters();
			$rb->disable_search();			
		$rb->set_defaults(array('receive'=>$arg['id']));
		$rpm = array(array('receive'=>$arg['id']), array(), array());
		$this->display_module($rb,$rpm,'show_data');
	}
	private function leightbox_new_delivery($prompt_id)
	{
		$theme = Base_ThemeCommon::init_smarty();		
				
		$form = $this->form_new_delivery($prompt_id);		
		
		$theme->assign('delivery_just_close',
			array(
				'open'=>'<a id="'.$prompt_id.'_just_close_button" onclick="if(check_for_save_delivery()) {leightbox_deactivate(\''.$prompt_id.'\');' . $form->get_submit_form_js(true) . '}">',
				'text'=>__( 'Save'),
				'close'=>'</a>'
			)
		);
		
		$form->assign_theme('form',$theme);
		
		ob_start(); 
		Base_ThemeCommon::display_smarty($theme,'SCTV_Warehouse','delivery_to_employee');		
		$profiles_out = ob_get_clean();
				
        return $profiles_out;	
	}
	private function form_new_delivery($prompt_id)
	{		
		$form = $this->init_module('Libs/QuickForm');					
					
		$delivery_date = $form->addElement('datepicker', 'delivery_date', __('Delivery Date'));
		$form->addRule('delivery_date','required', 'required', null, 'client');		
				
		$delivery_employee = $form->addElement('autoselect', 'delivery_employee', _M('Employee'), array(), array(array('CRM_ContactsCommon','autoselect_contact_suggestbox'), array(array('manager'=>$this->manager_id), array('param'=>'Last Name|First Name'), array('CRM_ContactsCommon', 'contact_format_default'))), array('CRM_ContactsCommon', 'contact_format_default'));
		$form->addRule('delivery_employee','required', 'required');
		
		$form->addElement('text', 'delivery_note', __('Note'));
		
		$recs = Utils_RecordBrowserCommon::get_records('SCTV_Material', array('ordinary'=>1), array(), array('material_code'=>'ASC'));			
		
		$defaults = array();
		$row = 0;

		foreach($recs as $rec){
			$material_element_name = 'delivery['.$row.'][material]';
			$material = $form->addElement(
				'autoselect', 
				$material_element_name, 
				_M('Material'), 
				array(), array(array('SCTV_MaterialCommon','material_suggestbox'), array(array(), array(), array('SCTV_MaterialCommon', 'material_format'))), array('SCTV_MaterialCommon', 'material_format'),
				array()
			);
			
			$defaults += array($material_element_name=>$rec['id']);

			$form->addElement('text', 'delivery[' . $row . '][amount]', __('Code'));
			$form->addElement('text', 'delivery[' . $row . '][note]', __('Note'));
						
			$row++;
		}			
				
		for($i = $row; $i < $row+5; $i++)
		{
			$material_element_name = 'delivery['.$i.'][material]';
			$material = $form->addElement(
				'autoselect', 
				$material_element_name, 
				_M('Material'), 
				array(), array(array('SCTV_MaterialCommon','material_suggestbox'), array(array(), array(), array('SCTV_MaterialCommon', 'material_format'))), array('SCTV_MaterialCommon', 'material_format'),
				array()
			);
			
			$form->addElement('text', 'delivery[' . $i . '][amount]', __('Code'));
			$form->addElement('text', 'delivery[' . $i . '][note]', __('Note'));							
		}

		$form->setDefaults($defaults);		
		
		if($form->validate())
		{
			$this->values = $form->exportValues();			
		}
		else {			
		}
		
		$delivery_date_id = $delivery_date->getType(). '_field_'. $delivery_date->getName();
		$delivery_date_error_id = 'error_' . $form->get_name() . '_' . $delivery_date->getName() . '_' . $delivery_date->getType();
		
		$delivery_employee_id = $delivery_employee->getName();
		$delivery_employee_error_id = 'error_' . $form->get_name() . '_' . $delivery_employee->getName() . '_' . $delivery_employee->getType();
		
		$required_error = __('Required');
		$required_error .= Libs_QuickFormCommon::get_error_closing_button();				
		 
		eval_js('check_for_save_delivery = function()
			{
				ok = true;
				
				deploymentdate = $(\'' . $delivery_date_id .'\').value;
				if(!deploymentdate)
				{
					$(\''.$delivery_date_error_id.'\').innerHTML=\''. Epesi::escapeJS($required_error) .'\';				
					ok = false;	
				}
				else {
					$(\''.$delivery_date_error_id.'\').innerHTML=\'\';
				}
				
				var employee_select = $(\''. $delivery_employee_id .'\');
				if(employee_select == null || employee_select.value == \'\')
				{
					$(\''.$delivery_employee_error_id.'\').innerHTML=\''. Epesi::escapeJS($required_error) .'\';				
					ok = false;	
				}
				else {
					$(\''.$delivery_employee_error_id.'\').innerHTML=\'\';
				}
				
				return ok;			
			}'
		);
							
        return $form;	
	}
	private function save_delivery_to_employee()
	{
		$id = Utils_RecordBrowserCommon::new_record('SCTV_DeliveryToEmployee', array(
					'delivery_date'=>$this->values['delivery_date'],
					'code'=>$this->values['delivery_code'],
					'employee'=>$this->values['delivery_employee'],
					'note'=>$this->values['delivery_note']
			));
			
			foreach ($this->values['delivery'] as $key => $value) {
				if(!empty($value['material']) && !empty($value['amount']) && $value['amount'] > 0)
				{
					Utils_RecordBrowserCommon::new_record('SCTV_DeliveryMaterial', array(
						'delivery'=>$id,
						'material'=>$value['material'],
						'amount'=>$value['amount'],
						'note'=>$value['note']
					));	
				}				
			}
		return $id;
	}
	
	private function leightbox_new_receive($prompt_id)
	{
		$theme = Base_ThemeCommon::init_smarty();		
				
		$form = $this->form_new_receive($prompt_id);		
		
		$theme->assign('receive_just_close',
			array(
				'open'=>'<a id="'.$prompt_id.'_just_close_button" onclick="if(check_for_save_receive()) {leightbox_deactivate(\''.$prompt_id.'\');' . $form->get_submit_form_js(true) . '}">',
				'text'=>__( 'Save'),
				'close'=>'</a>'
			)
		);
		
		$form->assign_theme('form',$theme);
		
		ob_start(); 
		Base_ThemeCommon::display_smarty($theme,'SCTV_Warehouse','receive_from_employee');		
		$profiles_out = ob_get_clean();
				
        return $profiles_out;	
	}
	private function form_new_receive($prompt_id)
	{		
		$form = $this->init_module('Libs/QuickForm');					
					
		$receive_date = $form->addElement('datepicker', 'receive_date', __('Receive Date'));
		$form->addRule('receive_date','required', 'required');		
				
		$receive_employee = $form->addElement('autoselect', 'receive_employee', _M('Employee'), array(), array(array('CRM_ContactsCommon','autoselect_contact_suggestbox'), array(array('manager'=>$this->manager_id), array('param'=>'Last Name|First Name'), array('CRM_ContactsCommon', 'contact_format_default'))), array('CRM_ContactsCommon', 'contact_format_default'));
		$form->addRule('receive_employee','required', 'required');
		
		$form->addElement('text', 'receive_note', __('Note'));
		
		$recs = Utils_RecordBrowserCommon::get_records('SCTV_Material', array('ordinary'=>1), array(), array('material_code'=>'ASC'));		
		$defaults = array();
		$row = 0;

		foreach($recs as $rec){
			$material_element_name = 'receive['.$row.'][material]';
			$material = $form->addElement(
				'autoselect', 
				$material_element_name, 
				_M('Material'), 
				array(), array(array('SCTV_MaterialCommon','material_suggestbox'), array(array(), array(), array('SCTV_MaterialCommon', 'material_format'))), array('SCTV_MaterialCommon', 'material_format'),
				array()
			);
			$defaults += array($material_element_name=>$rec['id']);
			
			$form->addElement('text', 'receive[' . $row . '][amount]', __('Code'));
			$form->addElement('text', 'receive[' . $row . '][note]', __('Note'));
						
			$row++;
		}			
				
		for($i = $row; $i < $row+5; $i++)
		{			
			$material_element_name = 'receive['.$i.'][material]';
			$material = $form->addElement(
				'autoselect', 
				$material_element_name, 
				_M('Material'), 
				array(), array(array('SCTV_MaterialCommon','material_suggestbox'), array(array(), array(), array('SCTV_MaterialCommon', 'material_format'))), array('SCTV_MaterialCommon', 'material_format'),
				array()
			);
			
			$form->addElement('text', 'receive[' . $i . '][amount]', __('Code'));
			$form->addElement('text', 'receive[' . $i . '][note]', __('Note'));
		}
		
		$form->setDefaults($defaults);
		
		if($form->validate())
		{
			$this->values = $form->exportValues();			
		}
		else {			
		}
		
		$receive_date_id = $receive_date->getType(). '_field_'. $receive_date->getName();
		$receive_date_error_id = 'error_' . $form->get_name() . '_' . $receive_date->getName() . '_' . $receive_date->getType();
		
		$receive_employee_id = $receive_employee->getName();
		$receive_employee_error_id = 'error_' . $form->get_name() . '_' . $receive_employee->getName() . '_' . $receive_employee->getType();
		
		$required_error = __('Required');
		$required_error .= Libs_QuickFormCommon::get_error_closing_button();				
		 
		eval_js('check_for_save_receive = function()
			{
				ok = true;
				
				deploymentdate = $(\'' . $receive_date_id .'\').value;
				if(!deploymentdate)
				{
					$(\''.$receive_date_error_id.'\').innerHTML=\''. Epesi::escapeJS($required_error) .'\';				
					ok = false;	
				}
				else {
					$(\''.$receive_date_error_id.'\').innerHTML=\'\';
				}
				
				var employee_select = $(\''. $receive_employee_id .'\');
				if(employee_select == null || employee_select.value == \'\')
				{
					$(\''.$receive_employee_error_id.'\').innerHTML=\''. Epesi::escapeJS($required_error) .'\';				
					ok = false;	
				}
				else {
					$(\''.$receive_employee_error_id.'\').innerHTML=\'\';
				}
				
				return ok;			
			}'
		);
							
        return $form;	
	}
	private function save_receive_from_employee()
	{
		$id = Utils_RecordBrowserCommon::new_record('SCTV_ReceiveFromEmployee', array(
					'receive_date'=>$this->values['receive_date'],
					'code'=>$this->values['receive_code'],
					'employee'=>$this->values['receive_employee'],
					'note'=>$this->values['receive_note']
			));
			
			foreach ($this->values['receive'] as $key => $value) {
				if(!empty($value['material']) && !empty($value['amount']) && $value['amount'] > 0)
				{
					Utils_RecordBrowserCommon::new_record('SCTV_ReceiveMaterial', array(
						'receive'=>$id,
						'material'=>$value['material'],
						'amount'=>$value['amount'],
						'note'=>$value['note']
					));	
				}				
			}
		return $id;
	}
}
 
?>